package com.jwaoo.mobile.view.login;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.CheckableImageButton;
import android.support.design.widget.TextInputLayout;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.widget.TextViewCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;
import com.dx.as.JWCache;
import com.dx.as.LoadingDialog;
import com.dx.as.ToastUtil;
import com.dx.as.UI;
import com.dx.as.common.CommonUtils;
import com.dx.as.common.JWConstant;
import com.dx.as.common.log.LogUtil;
import com.dx.as.common.string.StringUtil;
import com.dx.as.permission.MPermission;
import com.dx.as.permission.annotation.OnMPermissionDenied;
import com.dx.as.permission.annotation.OnMPermissionGranted;
import com.dx.as.permission.annotation.OnMPermissionNeverAskAgain;
import com.dx.as.utils.AESSecurityUtil;
import com.jwaoo.chat.ChatHelpter;
import com.jwaoo.mobile.ApplicationHelper;
import com.jwaoo.mobile.forchat.IFroChatMouleImpl;
import com.jwaoo.mobile.view.forgotpassword.ForgotPasswordActivity;
import com.jwaoo.mobile.view.forgotpassword.UpdatePasswordActivity;
import com.jwaoo.mobile.view.login.presenter.ILoginView;
import com.jwaoo.mobile.view.login.presenter.LoginPresenter;
import com.jwaoo.mobile.R;
import com.jwaoo.mobile.view.main.MainActivity;
import com.jwaoo.mobile.view.register.RegisterActivity;
import static com.jwaoo.mobile.view.forgotpassword.ForgotPasswordActivity.REQUEST_CODE;

public class LoginActivity extends UI implements ILoginView{
    private EditText edt_email;
    private EditText edt_password;
    private TextInputLayout lb_password;
    private boolean isKickedOffline = false;
    private LoginPresenter presenter;
    private Button btn_login_password;
    private boolean [] isComplete = new boolean[2];
    private long previousTime ;
    private String orgPassword;
    private final int BASIC_PERMISSION_REQUEST_CODE = 100;
    private Drawable [] drawablePassword;
    private Drawable [] drawableEmail;
    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        initView();
        initData();
    }

    private void initView(){
        edt_email = findView(R.id.edt_email);
        edt_password = findView(R.id.edt_password);
        lb_password = findView(R.id.lb_password);
        btn_login_password = findView(R.id.btn_login_password);
        edt_email.addTextChangedListener(textWatcher);
        edt_password.addTextChangedListener(textWatcher);
        final GestureDetectorCompat mDetector = new GestureDetectorCompat(ChatHelpter.getContext(),onGestureListener);
        edt_password.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mDetector.onTouchEvent(event);
                return false;
            }
        });
        presenter = new LoginPresenter(this,this);

    }


    @Override
    protected void onResume() {
        super.onResume();
        String account = CommonUtils.getAccount();
        if (!StringUtil.isEmpty(account)) {
            edt_email.setText(account);
            isComplete[0] = true;
        }
    }

    private void initData(){
        requestBasicPermission();
        setToolbar(null);
        isKickedOffline = getIntent().getBooleanExtra(JWCache.EXTRA_ONKICKED_OFF_LINE,false);
        if (isKickedOffline) {
            CommonUtils.clearAccountInfo();
            ToastUtil.makeText(this, "账号在异地登陆！").show();
        }

        if (Build.VERSION.SDK_INT >= 21) {
            drawablePassword = new Drawable[]{getDrawable(R.drawable.signup_hide_password_icon),getDrawable(R.drawable.signup__show_password_icon)};
            drawableEmail = new Drawable[]{getDrawable(R.drawable.signup_error_icon),getDrawable(R.drawable.signup_right_icon)};
        }

    }

    public void onViewClick(View view){
        switch (view.getId()){
            case R.id.tv_forgot:
                onForgotPassword();
                break;
            case R.id.v_sign_up:
                onSignUp();
                break;
            case R.id.btn_login_password:
                onLoginByPassword();
                break;
            case R.id.btn_login_facebook:
                onLoginByFaceBook();
                break;
            case R.id.btn_login_twitter:
                onLoginByTwitter();
                break;
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (edt_email.isFocused()){
                checkEmail(s.toString());
            }else if (edt_password.isFocused()){
                checkPassword(s.toString());
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    private void onLoginByPassword() {
        String email = edt_email.getText().toString();
        String password = edt_password.getText().toString();
        CommonUtils.saveAccount(email);
        try {
            password = new String(AESSecurityUtil.encrypt(password, JWConstant.KEY_AES));
            orgPassword = password;
        }catch (Exception ex){}
        showKeyboard(false);
        LoadingDialog.getInstance(this).show();
        Map<String,Object> map = new HashMap<>();
        map.put("account",email);
        map.put("password",password);
        map.put("type",1);
        presenter.doLogin(map);
    }

    private void onLoginByFaceBook() {

    }

    private void onLoginByTwitter() {

    }


    private void onForgotPassword(){
        goToNewActivityForResult(ForgotPasswordActivity.class, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            showSnackBar("The dynamic password has been sent");
        }
    }

    private void onSignUp(){
        goToNewActivity(RegisterActivity.class);
    }

    @Override
    public void onGetAccountInfo(boolean isLocked) {
        ApplicationHelper.initTools();
        IFroChatMouleImpl.getInstance().loginChatSystem();
        LoadingDialog.getInstance(JWCache.getContext()).dismiss();
        if (isLocked){
            onLocked();
        }else {
            goToNewActivity(MainActivity.class);
            finish();
        }

    }

    @Override
    public void onNotPerfect() {
        //完善资料
    }

    @Override
    public void onLocked() {
        //重置密码
        Bundle bundle = new Bundle();
        bundle.putString(UpdatePasswordActivity.password,orgPassword);
        bundle.putBoolean(UpdatePasswordActivity.isFormLogin,true);
        goToNewActivity(UpdatePasswordActivity.class,bundle);
        finish();
    }

    @Override
    public void onEmailNotverified(String errorMsg) {
        new AlertDialog.Builder(this).setMessage(R.string.account_not_verified).setNegativeButton(R.string.i_see,null).show();
    }

    private void checkEmail(String email){
        if (CommonUtils.chekEmail(email)){
            isComplete[0] = true;
            if (changeButtonState()) btn_login_password.setEnabled(true);
            setDrawable(edt_email , drawableEmail[1]);
            return;
        }
        isComplete[0] = false;
        setDrawable(edt_email , drawableEmail[0]);
        btn_login_password.setEnabled(false);
    }

    private void checkPassword(String password){
        if (!StringUtil.isEmpty(password) && password.trim().length() >= 6) {
            lb_password.setErrorEnabled(false);
            isComplete[1] = true;
            if (changeButtonState()) btn_login_password.setEnabled(true);
            return;
        }
        lb_password.setErrorEnabled(true);
        lb_password.setError(getResources().getString(R.string.error_pasword));
        isComplete[1] = false;
        btn_login_password.setEnabled(false);
    }

    private boolean changeButtonState(){
        return isComplete[0] && isComplete[1];
    }

    @Override
    public void onBackPressed() {
        long current = System.currentTimeMillis();
        if (previousTime <= 0 || current - previousTime >= 1000){
            ToastUtil.showToast(this,"在按一次退出！");
            previousTime = current;
            return;
        }
        System.exit(0);
    }

    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.READ_PHONE_STATE,
            android.Manifest.permission.RECORD_AUDIO
    };

    private void requestBasicPermission() {
        MPermission.printMPermissionResult(true, this, BASIC_PERMISSIONS);
        MPermission.with(LoginActivity.this)
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
//        Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        Toast.makeText(this, "未全部授权，部分功能可能无法正常运行！", Toast.LENGTH_SHORT).show();
        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
    }

    private boolean isHide = true;

    private  GestureDetector.OnGestureListener onGestureListener = new GestureDetector.OnGestureListener(){
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (e.getX() > (edt_password.getRight() - drawablePassword[0].getMinimumWidth() -30)){
                isHide = !isHide;
                setDrawable(edt_password , isHide ? drawablePassword[0] : drawablePassword[1]);
                edt_password.setTransformationMethod(isHide ? PasswordTransformationMethod.getInstance() : HideReturnsTransformationMethod.getInstance());
            }
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }
    };

    private void setDrawable(EditText v ,Drawable drawable){
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),drawable.getMinimumHeight());
        v.setCompoundDrawables(null,null,drawable,null);
    }
}

